package com.rzico.sbl.ui.report.manager

import android.os.Bundle
import android.widget.TextView
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportSecondBinding
import com.rzico.sbl.model.ManagerOrderData
import com.rzico.sbl.model.ManagerOrderModel
import com.rzico.sbl.other.addTimeListener
import com.rzico.sbl.other.getBeforeDate
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.initChart
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportSecondViewModel
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseRootActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter

class ReportSecondActivity : BaseRootActivity() {

    private lateinit var mBinding: ActivityReportSecondBinding

    private var mChartModel: ManagerOrderModel? = null
    private var mOrderStarus = ""
    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()

    override fun getViewModel() = get<ReportSecondViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = ActivityReportSecondBinding.inflate(layoutInflater)
        setContentView(mBinding.root)

        transparentStatusBar()

        initListener()
        initData()
        initLayout()
        initTabLayout()

        getOrderData()
    }

    override fun initData() {
        mBinding.also {
            it.secondOrder.apply {
                initChart(
                    yAxisMinimum = 0f,
                    isLegend = true,
                    xSpaceEntry = 50f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (
                        mChartModel == null
                        || value.toInt() !in mChartModel!!.completed.indices
                    ) ""
                    else
                        mChartModel!!
                            .completed[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }
    }

    /**
     * 初始化布局
     */
    private fun initLayout() {
        mBinding.apply {
            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        if (!isLoadingMore) {
                            isLoadingMore = true
                            getData(pageNum)
                        }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<ManagerOrderData>(R.layout.item_report_barrel) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_barrel_title, bean.ename)
                            text(R.id.item_barrel_type, bean.orderStatus)
                            text(R.id.item_barrel_sn, bean.sn)
                            text(R.id.item_barrel_time, bean.createDate.getTimeString())
                            text(R.id.item_barrel_num, bean.subQuantity)
                            text(R.id.item_barrel_name_hint, "金额")
                            text(R.id.item_barrel_name, bean.amountPayable.formatDecimal())
                            text(R.id.item_barrel_shop_hint, "司机")
                            text(R.id.item_barrel_shop, bean.name)

                            clicked {
                                goToOrderDetail("orderSn" to bean.sn)
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    /**
     * 监听方法
     */
    override fun initListener() {
        mBinding.apply {
            secondOrderTime.addTimeListener { start, end, _ ->
                mBeginDate = start
                mEndDate = end

                getViewModel().cancelRequest()
                getOrderData()
                updateList()
            }
        }
    }

    /**
     * TabLayout 初始化
     */
    private fun initTabLayout() {
        mBinding
            .methodTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mOrderStarus = when (it.position) {
                                1 -> "unconfirmed"
                                2 -> "confirmed"
                                3 -> "completed"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "全部"
                    },
                    true
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待接单"
                    },
                    false
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "配送中"
                    },
                    false
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已完成"
                    },
                    false
                )
            }
    }

    /**
     * 设置曲线图数据
     */
    private fun setCharData() {
        mBinding.methodTab.apply {
            getTabAt(1)?.let { tab ->
                tab.customView
                    ?.find<BadgeTextView>(R.id.item_tab_num)
                    ?.setBadgeCount(mChartModel?.unconfirmed?.sumOf { it.subQuantity.intValue } ?: 0)
            }
            getTabAt(2)?.let { tab ->
                tab.customView
                    ?.find<BadgeTextView>(R.id.item_tab_num)
                    ?.setBadgeCount(mChartModel?.confirmed?.sumOf { it.subQuantity.intValue } ?: 0)
            }
        }

        mBinding
            .secondOrder
            .apply {
                if (mChartModel != null && (
                            !mChartModel?.unconfirmed.isNullOrEmpty()
                                    || !mChartModel?.confirmed.isNullOrEmpty()
                                    || !mChartModel?.completed.isNullOrEmpty()
                            )
                ) {
                    getViewModel()
                        .initGroupData(
                            lineChart = this,
                            entriesFirst = mChartModel!!
                                .unconfirmed
                                .mapIndexed { index, item ->
                                    BarEntry(index.toFloat(), item.subQuantity.toFloat())
                                },
                            entriesSecond = mChartModel!!
                                .confirmed
                                .mapIndexed { index, item ->
                                    BarEntry(index.toFloat(), item.subQuantity.toFloat())
                                },
                            entriesThird = mChartModel!!
                                .completed
                                .mapIndexed { index, item ->
                                    BarEntry(index.toFloat(), item.subQuantity.toFloat())
                                }
                        )
                } else clear()

                animateY(500)
            }
    }

    /**
     * 获取曲线图数据
     */
    private fun getOrderData() {
        getViewModel()
            .orderRangeList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { data ->
                    mChartModel = data

                    setCharData()
                }
            )
    }

    /**
     * 订单明细列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                status = mOrderStarus,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .swipeRefresh
                        .isRefreshing = false
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .swipeRefresh
            .isRefreshing = true

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}